package com.wendu.oa.config;


import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.FilterRegistration;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//@Configuration
public class WdConfig {

    /**
     * FilterRegistrationBean是springmvc提供的编程方式注册WebFilter的Bean对象，
     * 其作用等同于web.xml中的过滤器配置（或者等同于@WebFilter的作用）
     * @return
     */
    @Bean
    public FilterRegistrationBean<CorsFilter> corsFilterRegistrationBean(){
        CorsConfiguration config = new CorsConfiguration();//跨域配置对象


        //config.setAllowCredentials(true); //允许使用session
        config.addAllowedOrigin("*");//允许什么样的来源主机地址
        config.addAllowedHeader("*");//允许什么样的请求头
        config.addAllowedMethod("*");//允许什么样的请求方式

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);

        CorsFilter filter = new CorsFilter(source);

        FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>(filter);
        bean.setOrder(0);//设置过滤顺序，这里设置0，表该过滤器第一个执行

        return bean;

    }


    @Bean
    public WebMvcConfigurer webMvcConfigurer(){


        //new Object(){};//创建了Object的无名子类对象
       return new WebMvcConfigurer(){//创建了WebMvcConfigurer了无名子类对象


            //跨域配置
            //@Override
//            public void addCorsMappings(CorsRegistry registry) {
//                registry.addMapping("/**")//访问本应用的任何地址（不含服务器路径部分）都允许跨域
//                        .allowedOrigins("*") //允许什么样的来源主机访问（对服务器路径的配置）
//                        .allowedHeaders("*")//允许什么样的请求头访问
//                        .allowedMethods("GET","POST","PUT","DELETE","OPTIONS");
//            }


           //配置拦截器
           @Override
           public void addInterceptors(InterceptorRegistry registry) {
               registry
                       .addInterceptor(new WdHandlerInterceptor())
                       .addPathPatterns("/**");
           }
       };



    }
}
